<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Exams;
use app\admin\model\Questions;
use app\index\model\StuAnswers;
use app\admin\controller\Siku;
class Exam extends Siku
{
    
    public function index()
    {
        // $aa='1,2,5,18,23,24';
        // //$bb='['.$aa.']';
        //  $q =db('questions')->where('qid','in',$aa)->where('qtype','in','3,4')->order('sort asc')->select()->toArray();
        //  dump($q);
       //dump(json_encode(explode(',', '1,2,5,18,23,24')) );
        return $this->fetch();
    }
    

    public function edata()
    {
        $edata= new Exams();
        $limit=request()->param('limit');
        $page=request()->param('page');
        $map['subject']=request()->param('subject');
        //dump($map);
        $map = array_diff($map, array(null,'null','',' '));
        // $subsql1 = Db::table('siku_stu_answers')->field('eid an_eid,count(id) countan')->buildSql();
        // $list=Db::table('siku_exams')->alias('a')->join([$subsql1=> 'w'], 'a.eid = w.an_eid','LEFT')->page($page,$limit)->where($map)->order('eid desc')->select();
        $list=$edata->page($page,$limit)->where($map)->where('tid',session('uid'))->withCount('getstuanswers')->order('eid', 'desc')->select();
        //dump($list->toArray());
        $count=$edata->where($map)->where('tid',session('uid'))->count();
        return myjson(0,'',$count,$list);
    }
    public function add()
    {
        $classes=db('classes')->select();
        $this->assign('classes',$classes);
        return $this->fetch();
        
    }
    public function do_add(){
        
        if (request()->isPost()) {
            $formdata = request()->post();
            //return $formdata;
            //return json($data);
            if (!array_key_exists('cids', $formdata)) {
                return '没有选择参考班级！';
            }
            $formdata['cids']=implode(',', $formdata['cids']);
            date_default_timezone_set("PRC");
            $formdata['begintime']=strtotime($formdata['begintime']);
            //dump($formdata);
            $edata= new Exams;
            $a=$edata->allowField(true)->save($formdata);
            // //dump(input('post.'));
            // //dump($formdata);
            // //$userId = Db::name('data')->strict(false)->insertGetId($formdata);
            if ($a===false) {
                $re='添加数据库错误！';
            } else {
                $re=1;
            }
            return $re;
        }else{
            return '非法操作！';
        }
    }
    public function change_examstatus(){
        $formdata = request()->post();
        $eid=(intval($formdata['data']['eid']));
        $user = Exams::get($eid);
        $user->examstatus     = intval($formdata['data']['examstatus']);
        $re=$user->save();
        if ($re) {
            return 1;
        } else {
            return 2;
        }
        

    }
    public function edit(){
        $classes=db('classes')->where('grade',session('grade'))->select();
        $this->assign('classes',$classes);
        $id=request()->param('id');
        //echo $id;
        $re=Exams::get($id);
       //dump ($re['cids']==null);
        //dump($re->toArray());
        $this->assign('edata',$re);
        return $this->fetch();
    }
    public function do_edit(){
        
        if (request()->isPost()) {
            $formdata = request()->post();
            if (!array_key_exists('cids', $formdata)) {
                return '没有选择参考班级！';
            }
            //dump($formdata);
            $formdata['cids']=implode(',', $formdata['cids']);
            $formdata['begintime']=strtotime($formdata['begintime']);
             $edata= new Exams;
             $a=$edata->allowField(true)->where('eid', $formdata['eid'])->update($formdata);
            if ($a===false) {
                return '更新错误！';
            } else {
                return 1;
            }
        }else{
            return '非法操作！';
        }
        
    }
    public function del(){
        $id=request()->param('id');
        $re=db('exams')->delete($id);
        if ($re > 0) {
            $res=1;
        } else {
           $res='数据库错误';
        }
        return $res;
    }
    public function showstuanswers (){
        $eid=request()->param('id');
        //echo $eid;
        $title=db('exams')->where('eid',$eid)->value('title');
        $this->assign('title',$title);
        $this->assign('eid',$eid);
        return $this->fetch();
    }
    public function showstuanswers_data(){
        $eid=request()->param('eid');
        $limit=request()->param('limit');
        $page=request()->param('page');
        $map['truename']=request()->param('truename');
        $map['class']=request()->param('class');
        $map = array_diff($map, array(null,'null','',' '));
        $stuanswer=new StuAnswers();
        $subsql = Db::table('siku_students')->where($map)->buildSql();
        $stuandata=$stuanswer->page($page,$limit)->alias('a')->join([$subsql=> 'w'], 'a.sid = w.sid')->where('eid',$eid)->with('getstudent')->select();
        $count=$stuanswer->alias('a')->join([$subsql=> 'w'], 'a.sid = w.sid')->where('eid',$eid)->with('getstudent')->count();
        //dump($stuandata);
        return myjson(0,'',$count,$stuandata);

    }

    public function add_q_to_exam(){
        $question_ids=request()->param('id');
        //dump($qids);
        $exams=Exams::all(function($query){$query->where('tid', session('uid'))->where('subject',session('subject'))->order('eid', 'asc');})->toArray();
        //dump($exams);
        $empty='<div style="padding: 15px;color:red;">您尚未创建任何考试项目</div>';
        $this->assign('empty',$empty);
        $this->assign('qids',$question_ids);
        $this->assign('exams',$exams);
        return $this->fetch();
    }
    public function do_add_q_to_exam(){
        $formdata=request()->param();
        //dump($formdata);
        if (!array_key_exists('eid', $formdata)) {
           return '您没有选择要加入的试卷！';
        } else {
           $edata = Exams::get($formdata['eid']);
           //add_question_str处理添加题到试卷的函数公共里面
           $edata->qids=add_question_str($edata->qids,$formdata['qids']);
           $re=$edata->save();
           if ($re===1) {
                Db::name('questions')->where('qid','in',$formdata['qids'])->setField('qstatus', 1);
               return 1;
           } else {
               return '添加重复或失败！';
           }
        }
        
    }
    public function view(){
        $eid=request()->param('id');
        //dump($formdata);
        $edata=Exams::get($eid)->toArray();
        $this->assign('edata',$edata);
        return $this->fetch();
    }
    public function view_data()
    {
        $qids=request()->param('qids');
        //dump($edata);
         $list = new Questions;
         $with['getanswers']=function($query){$query->order(['aid'=>'asc']);};
        $qdata =$list->with($with)->where('qid','in',$qids)->order('sort asc')->select();
        $count=$qdata->count();
        // //dump($qdata);
    
        // // $data=array('qdata' => $1data);
          return myjson(0,'',$count,$qdata);
    }
    public function change_sort_score(){
        $change_data=request()->post();
       // dump($change_data);
        $user = new Questions;
        $re=$user->where('qid', $change_data['qid'])->update([$change_data['field'] => $change_data['value']]);
        return $re;

    }
    public function del_exam_question(){
        $qid=request()->param('id');
        $eid=request()->param('eid');
        $edata = Exams::get($eid);
       //del_question_str公共函数里面
        $edata->qids=del_question_str($edata->qids,$qid);
        $re=$edata->save();
        if ($re===1) {
               return 1;
        } else {
               return '删除失败！';
        }
    }
    public function marking(){
        
       return $this->fetch();
    }
    public function markdata(){
        $edata= new Exams();
        $limit=request()->param('limit');
        $page=request()->param('page');
        $list=$edata->page($page,$limit)->where('find_in_set(:tid,tids)',['tid'=>session('uid')])->withCount('getstuanswers')->withCount(['getmarkcount'=>function($query){$query->where('mark_tid',session('uid'));}])->order('eid', 'desc')->select();
        //dump($list->toArray());
        $count=$edata->where('find_in_set(:tid,tids)',['tid'=>session('uid')])->count();
        return myjson(0,'',$count,$list);
    }
    // public function markpaper(){
    //     $this->assign('eid',request()->param('id'));
    //     return $this->fetch();
    // }
    public function markpaper(){
        $requ=request()->param();
        //dump($requ);
        if (!array_key_exists('action', $requ)) {
            $requ['action']='';
        }
        $endid=$requ['endid'];$starid=$requ['starid'];
        $where['eid']=$requ['eid'];
        if ($requ['action']=='previous') {
            $where['id']=$requ['id']-1;
        } else{
            //$where['id']=$requ['id']+1;
            $where['mark_tid']=null;
            $where['id']= ['between',[$starid,$endid]];
        }
        $edata=new StuAnswers();
        $myexam=$edata->with('getexams')->where($where)->order('id', 'asc')->find();
        //dump($myexam);
        //echo time();
        if(time()<$myexam['getexams']['begintime']+$myexam['getexams']['timelong']*60){
            echo '本次考试尚未结束！待结束后再阅！';die();
        }else{
            $list = new Questions;
            // $with['getanswers'] = function ($query) {
            //         $query->order(['aid' => 'asc']);
            //     };
            $qdata =$list->where('qid','in',$myexam['getexams']['qids'])->where('qtype','in','3,4')->order('sort asc')->select()->toArray();
            $this->assign('myexam',$myexam);
            $this->assign('mystartid',$myexam['getexams']['allocate'][session('uid')][1]);
           $this->assign('myendid',($myexam['getexams']['allocate'][session('uid')][1]+intval($myexam['getexams']['allocate'][session('uid')][0])-1));
            $this->assign('qdata',$qdata);
            //dump($qdata);
            return $this->fetch();
            //return myjson(0,'',1,$markdata);

        }
        
    }
    public function markpaper_click(){//原来的上下页
        $requ=request()->param();
        //dump($requ);
        $where['eid']=$requ['eid'];
        if ($requ['action']=='previous') {
            $where['id']=$requ['id']-1;
        } elseif ($requ['action']=='next') {
            $where['id']=$requ['id']+1;
        }
        $edata=new StuAnswers();
        $myexam=$edata->with('getexams')->order('id', 'asc')->where($where)->find()->toArray();
        //dump($myexam);
        //echo time();
        $list = new Questions;
        // $with['getanswers'] = function ($query) {
        //         $query->order(['aid' => 'asc']);
        //     };
        $qdata =$list->where('qid','in',$myexam['getexams']['qids'])->where('qtype','in','3,4')->order('sort asc')->select()->toArray();
        $this->assign('myexam',$myexam);
        $this->assign('mystartid',$myexam['getexams']['allocate'][session('uid')][1]);
        $this->assign('myendid',($myexam['getexams']['allocate'][session('uid')][1]+intval($myexam['getexams']['allocate'][session('uid')][0])-1));
        $this->assign('qdata',$qdata);
        //dump($qdata);
        return $this->fetch('markpaper');
        //return myjson(0,'',1,$markdata);

        
    }
     public function do_mark(){
        $requ=request()->param();
        //dump($requ);
        $starid=$requ['starid'];
        $endid=$requ['endid'];
        $eid=$requ['eid'];
        $where['eid']=$requ['eid'];
        $where['id']=$requ['id'];
       foreach ($requ['score'] as $k => $v) { $markscore[$k]=intval($v); }
        $edata=new StuAnswers();
        $myexam=$edata->where($where)->value('score');
        //dump($myexam);
        $allscorearr=array_replace(json_decode($myexam,true), $markscore);
        //dump(json_encode($allscorearr));
        $re=$edata->where('id', $requ['id'])->update(['score' => json_encode($allscorearr),'total'=>array_sum($allscorearr),'mark_tid'=>session('uid')]);
        if ($re===false) {
                //return '提交错误，请刷新重试！';
                $this->error('提交错误，请刷新重试！');
            } else {
                if ($requ['id'] >= $requ['endid']) {
                    $this->success('您的试题已经全部判完！','','',10);
                } else {
                    $this->success('提交成功',url('Admin/exam/markpaper',['starid'=>$starid,'eid'=>$eid,'action'=>'next','endid'=>$endid]),'',1);
                }
                
                
                //return 1;
            }

        
    }

    public function allocate(){
        $formdata=request()->param();
        //dump($formdata);
        $teachers=db('teachers')->where('grade',session('grade'))->where('subject',session('subject'))->field('tid,truename')->select()->toArray();
        //dump($teachers);
        $ed= new Exams();
        $edata=$ed->where('eid',$formdata['id'])->withCount('getstuanswers')->find()->toArray();
        //dump($edata);
        if ($edata['allocate']=='' || $edata['allocate']==null) {
            $allocate=array();
        } else {
            $allocate=$edata['allocate'];
        }
        //dump($allocate);
        $this->assign('teachers',$teachers);
        $this->assign('total',$edata['getstuanswers_count']);
        $this->assign('allocate',$allocate);
        $this->assign('eid',$edata['eid']);
        return $this->fetch();
    }
    public function do_allocate(){
        
        if (request()->isPost()) {
            $formdata = request()->post();
            if (!array_key_exists('tids', $formdata)) {
                return '没有选择阅卷教师！';
            }
            //dump($formdata);
            $ar=array_intersect_key($formdata['allocate'],array_flip($formdata['tids']));
            //dump ($ar);
            //学生试卷的开始id
            $startid=db('stu_answers')->where('eid', $formdata['eid'])->order('id asc')->value('id');
            //dump($startid);
            foreach (array_keys($ar) as $tid) {
                $arr[$tid]=[$ar[$tid],$startid];$startid=$startid+$ar[$tid];
            }
            //dump($arr);
            $allocate=json_encode($arr);
            $edata= new Exams;
            $a=$edata->allowField(true)->where('eid', $formdata['eid'])->update(['allocate' => $allocate,'tids' =>implode(',', array_keys($ar))]);
            if ($a===false) {
                return '更新错误！';
            } else {
                return 1;
            }
        }else{
            return '非法操作！';
        }
        
    }
    //判断试卷是否需要人工判卷（是否存在3.4题型）
    public function check_mark_human(){
        //$myqids=json_decode($qdata,true);
        //$myqids=implode(',', $qids);
        $qids=request()->param('qids');
        $where['qtype']=['in','3,4'];
        $where['qid']= ['in',$qids];
        $q =Db::name('questions')->where($where)->select()->toArray();
        if (empty($q)) {
            return 0;
        }else{
            return 1;
        }
        //return $q;
    }




}
